package servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/upload")
public class FileUploadServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("FileUploadServlet.service()");

        response.setContentType("text/plain;charset=utf-8");

        PrintWriter out=response.getWriter();

        // String name=request.getParameter("name");
        // String file=request.getParameter("file");
        //
        //
        // System.out.println("name = " + name);
        // System.out.println("file = " + file);


        // InputStream in=request.getInputStream();
        //
        // byte[] b=new byte[20480];
        //
        // int n;
        //
        // while((n=in.read(b))!=-1){
        //     System.out.print(new String(b,0,n));
        // }


        DiskFileItemFactory factory=new DiskFileItemFactory();


        //解析工具
        ServletFileUpload fileUpload=new ServletFileUpload(factory);


        try {
            List<FileItem> items=fileUpload.parseRequest(request);

            //因为返回的是List类型
            //跟以前request.getParameter()操作Map结果不一样
            //使用起来不方便
            //自己转换成Map
            Map<String,FileItem> map=new HashMap<String,FileItem>();
            for (FileItem item : items) {
                // System.out.println(item.getFieldName());
                map.put(item.getFieldName(),item);
            }






            String name=map.get("name").getString();

            System.out.println("name = " + name);


            FileItem file=map.get("file");

            System.out.println("file.getName() = " + file.getName());
            System.out.println("file.getContentType() = " + file.getContentType());
            System.out.println("file.getSize() = " + file.getSize());

            if(file.getName().endsWith(".jsp")){
                request.setAttribute("message","不能上传.jsp文件");
                request.getRequestDispatcher("/fileupload.jsp").forward(request,response);
                return;
            }


            // ServletContext application=getServletContext();
            //
            // String uploadDir=application.getRealPath("fileuplad");
            //
            // System.out.println("uploadDir = " + uploadDir);
            //
            // file.write(new File(uploadDir,file.getName()));
















        } catch (Exception e) {
            e.printStackTrace();
        }



        out.print("文件上传成功");
    }
}
